import React, { Component, Suspense } from 'react'
import { Route, Switch, withRouter, Redirect } from 'react-router-dom'
import { inject, observer } from 'mobx-react'
import { FullScreenLoading } from '@/components'
import routes from './routes'

@withRouter
@inject('request', 'user', 'historyStore')
@observer
class App extends Component {
  state = { serverConnected: false }

  componentDidMount() {
    this.connectServer()
    this.bindHistory()
  }

  connectServer = async () => {
    try {
      // 尝试登录
      await this.props.user.autoLogin()
    } catch (err) {
      console.error('服务器链接失败', err)
    } finally {
      // 无论是否成功,都设置已经连接
      this.setState({ serverConnected: true })
    }
  }

  bindHistory = () => {
    this.props.historyStore.setHistory(this.props.history)
  }

  renderRoute = (item = {}) => {
    const { path, component, auth = true, ...rest } = item
    const isLogin = this.props.user.isLogin
    const shouldRender = auth ? isLogin : true

    return shouldRender ? <Route key={path} path={path} component={component} {...rest} /> : null
  }

  render() {
    return (
      <>
        <Suspense fallback={<FullScreenLoading loading />}>
          {this.state.serverConnected && (
            <Switch>
              {routes.map(this.renderRoute)}

              <Redirect to='/login' />
            </Switch>
          )}
        </Suspense>

        <FullScreenLoading loading={this.props.request.isFetching} />
      </>
    )
  }
}

export default App
